/**
 * @Author: wanqian
 * @Date: 2021/3/27 11:15
 */
public class CircleArray {

    private int[] arr;

    private int maxSize;

    private int front;

    private int rear;

    public CircleArray(int maxSize) {
        this.arr = new int[maxSize];
        this.maxSize = maxSize;
    }

    public void add(int i) {
        if (isFull()) {
            System.out.println("队列已满");
            return;
        }

        arr[rear] = i;
        rear = (rear + 1) % maxSize;
    }

    public int get() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        int result = arr[front];
        front = (front + 1) % maxSize;
        return result;
    }

    public void list() {
        for (int i = front; i < front + length(); i++) {
            System.out.println(String.format("arr[%d] = %d", i, arr[i % arr.length]));
        }
    }

    public int length() {
        return (rear - front + maxSize) % maxSize;
    }

    public boolean isEmpty() {
        return rear == front;
    }

    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    public static void main(String[] args) {
        CircleArray array = new CircleArray(5);
        try {
            array.get();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        array.add(1);
        array.add(2);
        array.add(3);
        array.add(4);
        array.add(5);
        array.add(6);
        array.list();
        System.out.println(array.get());
        System.out.println(array.get());
        System.out.println(array.get());
        System.out.println(array.get());
        System.out.println(array.get());
        System.out.println(array.get());

    }
}
